package one.stand.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jmp.api.admin.dto.CompanySuncodeRequest;
import com.jmp.api.admin.dto.*;
import com.jmp.api.admin.entity.CompanyInfoEntity;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.ArticleApi;
import com.jmp.base.LabelApi;
import com.jmp.base.dto.*;
import com.jmp.feign.CompanyFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.dto.Company2Dto;
import one.stand.dto.CompanyServiceDto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.mapper.CompanyApiAdminMapper;
import one.stand.mapper.CompanyPlatformMapperApiCrmPcExt;
import one.stand.model.*;
import one.stand.request.CompanyRequest;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.CompanyShowroomService;
import one.stand.util.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @author: ZRH
 * @CreateDate: 2019/4/17 9:45
 */
@RestController
@RequestMapping("adminApi/company")
@Api(description = "总后台公司管理")
@Slf4j
public class CompanyController extends BaseController {
    @Autowired
    private CompanyFeign companyFeign;

    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyShowroomService companyShowroomService;

    @Autowired
    private CompanyApiAdminMapper companyApiAdminMapper;
    @Autowired
    private CompanyPlatformMapperApiCrmPcExt companyPlatformMapperApiCrmPcExt;

    @ApiOperation(value = "审核公司")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "auditState", value = "状态", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "auditRemark", value = "备注", paramType = "String"),
    })
    @PostMapping("auditCompany")
    @SecurityAuthCheck
    public ResultModel auditCompany(CompanyRequest request) {
        return adminFegin.auditCompany(request);
    }

    @ApiOperation(value = "公司购买名片服务数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "purchaseNum", value = "购买数量", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "payNum", value = "支付金额", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "endTime", value = "到期时间", required = true, paramType = "String"),
            @ApiImplicitParam(name = "isAgent", value = "公司是否代理:0不是代理商  1是", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "companyType", value = "1、服务（普通），2、源码（高级）", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "agentMoney", value = "公司代理金额", paramType = "Integer"),
    })
    @PostMapping("addCompanyService")
    @SecurityAuthCheck
    public ResultModel addCompanyService(CompanyServiceAddApiRequest request) {
        log.info("公司购买名片服务数参数：{}", JSON.toJSONString(request));
        if (request == null || request.getCompanyId() == null) {
            return ResultModel.checkParamFail();
        }
        if (request.getPurchaseNum() == null || request.getPurchaseNum() <= 0) {
            return ResultModel.fail("请输入购买名片数~！");
        }
        if (StringUtils.isBlank(request.getEndTime())) {
            return ResultModel.fail("请输入到期时间~！");
        }
        if (request.getCompanyType() == null) {
            return ResultModel.fail("请选择购买版本~！");
        }
        if (request.getIsAgent() == null) {
            return ResultModel.fail("请选择企业类型~！");
        }

        Integer userId = RequestContextHolder.getRequestContext().getUser().getUserId();

        // 设置企业的购买版本，代理权限和代理价格
        ResultModel<Boolean> resultModel = adminFegin.configureAgen(new CompanyRequest() {{
            setCompanyId(request.getCompanyId());
            setCompanyType(request.getCompanyType());
            setIsAgent(request.getIsAgent());
            setAgentMoney(request.getAgentMoney());
            setId(Long.valueOf(userId));
        }});
        AssertUtil.isTrue(resultModel);

        // 企业服务购买
        CompanyServiceAddRequest serviceAddRequest = CompanyServiceAddRequest.builder()
                .companyId(request.getCompanyId())
                .endTime(request.getEndTime())
                .payNum(request.getPayNum())
                .purchaseNum(request.getPurchaseNum())
                .userId(userId)
                .build();
        ResultModel serviceAddResultModel = companyFeign.serviceAdd(serviceAddRequest);
        AssertUtil.isTrue(serviceAddResultModel);

        // 内容显示配置
        CompanyContentAddRequest contentAddRequest = CompanyContentAddRequest.builder()
                .companyId(request.getCompanyId())
                .build();
        if (Objects.nonNull(request.getContentShow()) && request.getContentShow() == 1) {
            companyFeign.contentAdd(contentAddRequest);
        } else {
            companyFeign.contentRemove(contentAddRequest);
        }

        // 店铺等级
        ResultModel levelUpdateResultModel = companyFeign.levelUpdate(CompanyLevelUpdateRequest.builder()
                .companyId(request.getCompanyId())
                .level(request.getCompanyLevel())
                .build());
        AssertUtil.isTrue(levelUpdateResultModel);

        //3d vr
        companyShowroomService.updateVrUrl(request.getCompanyId(), request.getVrUrl());

        return ResultModel.success(true);
    }

    @ApiOperation(value = "查询企业列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enterpriseType", value = "状态:1普通企业  2授权企业  3到期企业", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "companyName", value = "条件筛选", paramType = "String"),
    })
    @PostMapping("selectCompanyList")
    @SecurityAuthCheck
    public ResultModel<CompanySelectCompanyListResponse> selectCompanyList(CompanyListRequest request) {
        log.info("查询企业列表参数：{}", JSON.toJSONString(request));

        String searchNameLike = SqlUtil.like(request.getCompanyName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Company> list = companyApiAdminMapper.selectCompanyList(request.getEnterpriseType(), searchNameLike, request.getLabelId(), request.getPlatformId(), request.getType());
        AssertUtil.nonNull(list, ResultEnum.NO_DATA);

        List<CompanyPlatform> companyPlatforms = companyPlatformMapperApiCrmPcExt.selectPlatform();
        List<CompanySelectCompanyListResponse.Platform> platformList = ConvertUtils.list(companyPlatforms, companyPlatform -> {
            Optional<Company2Dto> company = companyBaseService.get(companyPlatform.getCompanyId());
            return CompanySelectCompanyListResponse.Platform.builder()
                    .id(companyPlatform.getId())
                    .name(company.map(Company2Dto::getCompanyName).orElse(null))
                    .build();
        });

        PageResponse2<CompanySelectCompanyListResponse.Company> pageInfo = ConvertUtils.page2(list, companyModel -> {

            BusinessCard businessCard = businessCardBaseService.getByUserId(companyModel.getUserId());
            Integer cardCount = businessCardBaseService.count(companyModel.getCompanyId());
//            Integer customerCount = businessCardBaseService.countCustomer(companyModel.getCompanyId());
            CompanyServiceDto companyServiceDto = companyBaseService.getService(companyModel.getCompanyId());
            List<String> labelNames = companyApiAdminMapper.selectLabelName(LabelApi.LABEL_TYPE_COMPANY, companyModel.getCompanyId());
            Integer type = companyApiAdminMapper.selectLicensesType(companyModel.getCompanyId());
            CompanyShowroom companyShowroom = companyShowroomService.getByCompanyId(companyModel.getCompanyId());

            return CompanySelectCompanyListResponse.Company.builder()
                    .companyId(companyModel.getCompanyId())
                    .companyName(companyModel.getCompanyName())
                    .isAgent(companyModel.getIsAgent())
                    .agentMoney(companyModel.getAgentMoney())
                    .createTime(companyModel.getCreateTime())
                    .companyType(companyModel.getCompanyType())
                    .companyLevel(companyModel.getCompanyLevel())

                    .allBusinessCardCount(cardCount)
//                    .allCustomerCount(customerCount)

                    .name(businessCard != null ? businessCard.getName() : "")
                    .phone(businessCard != null ? businessCard.getPhone() : "")
                    .personalWx(businessCard != null ? businessCard.getPersonalWx() : "")

                    .endTime(companyServiceDto.getEndTime())
                    .currentNum(companyServiceDto.getCurrentNum())
                    .availableNum(companyServiceDto.getAvailableNum())

                    .contentShow(BooleanUtils.toInteger(Objects.nonNull(companyApiAdminMapper.selectCompanyContentOne(companyModel.getCompanyId()))))

                    .labelNames(labelNames)
                    .type(Objects.nonNull(type) ? type : 0)// 0其他

                    .vrUrl(Objects.nonNull(companyShowroom) ? companyShowroom.getVrUrl() : null)

                    .build();
        });

        PageHelper.startPage(1, 100);// 100 标签应该不会超过100
        List<CompanyCustomerLable> labels = companyApiAdminMapper.selectLabel(ArticleApi.DEFAULT_COMPANYID, null);
        List<CompanySelectCompanyListResponse.Label> labelList = ConvertUtils.list(labels, label -> CompanySelectCompanyListResponse.Label.builder()
                .id(label.getLableId())
                .name(label.getLableName())
                .build());

        CompanySelectCompanyListResponse response = CompanySelectCompanyListResponse.builder()
                .pageInfo(pageInfo)
                .labelList(labelList)
                .platformList(platformList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "导出用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enterpriseType", value = "状态:1普通企业  2授权企业  3到期企业", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "companyName", value = "条件筛选", paramType = "String"),
    })
    @PostMapping("selectCompanyListExport")
    @SecurityAuthCheck
    public void selectCompanyListExport(CompanyListRequest request, HttpServletResponse response) throws IOException {
        log.info("导出企业列表参数：{}", JSON.toJSONString(request));
        String searchNameLike = SqlUtil.like(request.getCompanyName());
        List<Company> list = companyApiAdminMapper.selectCompanyList(request.getEnterpriseType(), searchNameLike, request.getLabelId(), request.getPlatformId(), request.getType());

        ExportDataDTO<CompanyExcelEntity> exportDataDTO = new ExportDataDTO<>();
        exportDataDTO.setSheetName("企业列表");
        exportDataDTO.setFileName("企业列表");
        exportDataDTO.setTitle("企业列表");
        if (OneListUtil.isNotEmpty(list)) {
            List<CompanyExcelEntity> excelEntities = ConvertUtils.list(list, model -> {
                BusinessCard businessCard = businessCardBaseService.getByUserId(model.getUserId());
                Integer cardCount = businessCardBaseService.count(model.getCompanyId());
                Integer customerCount = businessCardBaseService.countCustomer(model.getCompanyId());
                CompanyServiceDto companyServiceDto = companyBaseService.getService(model.getCompanyId());
                return CompanyExcelEntity.builder()
                        .companyId(model.getCompanyId())
                        .companyName(model.getCompanyName())
                        .allBusinessCardCount(cardCount)
                        .allCustomerCount(customerCount)
                        .name(businessCard.getName())
                        .phone(businessCard.getPhone())
                        .personalWx(businessCard.getPersonalWx())
                        .createTime(DateUtil.formatter.format(model.getCreateTime()))
                        .endTime(DateUtil.formatter.format(companyServiceDto.getEndTime()))
                        .build();
            });
            exportDataDTO.setDataList(excelEntities);
        }
        ExcelUtil.exportExcel(exportDataDTO, CompanyExcelEntity.class, response);
    }

    @ApiOperation(value = "查询企业信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
    })
    @PostMapping("getAdminCompanyInfo")
    @SecurityAuthCheck
    public ResultModel<CompanyInfoResponse> getAdminCompanyInfo(CompanyInfoRequest request) {
        log.info("查询企业信息参数：{}", JSON.toJSONString(request));
        if (request == null || request.getCompanyId() == null) {
            return ResultModel.noData();
        }
        Company company = companyBaseService.getById(request.getCompanyId());
        AssertUtil.nonNull(company, "企业不存在");
        AssertUtil.isTrue(company.getIsDel() == 0, "企业不存在");

        BusinessCard businessCard = businessCardBaseService.getByUserId(company.getUserId());
        CompanyInfoEntity companyInfoEntity = companyApiAdminMapper.selectCompanyInfo(request.getCompanyId());

        ResultModel<CompanyLicenseInfoResponse> licenseInfoResponseResultModel = companyFeign.licenseInfo(CompanyLicenseInfoRequest.builder().companyId(request.getCompanyId()).build());

        CompanyInfoResponse response = CompanyInfoResponse.builder()
                .companyId(company.getCompanyId())
                .companyLogo(company.getCompanyLogo())
                .companyName(company.getCompanyName())
                .companyNotice(company.getCompanyNotice())
                .isAgent(company.getIsAgent())
                .agentMoney(company.getAgentMoney())
                .createTime(company.getCreateTime())
                .licensePhotos(Objects.nonNull(licenseInfoResponseResultModel) && licenseInfoResponseResultModel.isSuccess() ? licenseInfoResponseResultModel.getData().getPhotos() : null)

                .name(businessCard.getName())
                .phone(businessCard.getPhone())
                .position(businessCard.getPosition())
                .personalWx(businessCard.getPersonalWx())
                .email(businessCard.getEmail())
                .wxTwoCode(businessCard.getWxTwoCode())

                .industryName(companyInfoEntity.getIndustryName())
                .allBusinessCardCount(companyInfoEntity.getAllBusinessCardCount())
                .allCustomerCount(companyInfoEntity.getAllCustomerCount())
                .endTime(companyInfoEntity.getEndTime())
                .currentNum(companyInfoEntity.getCurrentNum())

                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "查询代理商企业下公司的信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
    })
    @PostMapping("selectAgentCompanyList")
    @SecurityAuthCheck
    public ResultModel<Map<String, Object>> selectAgentCompanyList(CompanyRequest request) {
        log.info("查询代理商企业下公司的信息参数：{}", JSON.toJSONString(request));
        if (request == null || request.getCompanyId() == null) {
            return ResultModel.noData();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CompanyModel> list = companyApiAdminMapper.selectAgentCompanyList(new CompanyModel() {{
            setCompanyName(request.getCompanyName());
            setAgentCompanyId(request.getCompanyId());
        }});
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<CompanyModel> pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    @ApiOperation(value = "设置企业代理权限和代理价格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "agentMoney", value = "公司代理金额", paramType = "Integer"),
            @ApiImplicitParam(name = "isAgent", value = "公司是否代理0不是代理商  1是", paramType = "Integer"),
    })
    @PostMapping("configureAgen")
    @SecurityAuthCheck
    public ResultModel<Boolean> configureAgen(CompanyRequest request) {
        request.setId(Long.valueOf(RequestContextHolder.getRequestContext().getUser().getUserId()));
        return adminFegin.configureAgen(request);
    }

    @ApiOperation(value = "企业太阳码")
    @PostMapping("suncode")
    @SecurityAuthCheck
    public void suncode(CompanySuncodeRequest request, HttpServletResponse response) throws Exception {

        ResultModel<CompanySuncodeResponse> resultModel = companyFeign.suncode(com.jmp.base.dto.CompanySuncodeRequest.builder().companyId(request.getCompanyId()).build());
        AssertUtil.isTrue(resultModel);
        Optional<Company2Dto> company2DtoOptional = companyBaseService.get(request.getCompanyId());

        //设置响应类型，告诉浏览器当前是下载操作
//        response.setContentType("application/x-msdownload");
        response.setContentType("applicatoin/octet-stream");
        //设置下载时文件的显示类型(即文件名称-后缀)   ex：txt为文本类型
        response.setHeader("Content-Disposition", "attachment;filename=" + company2DtoOptional.map(Company2Dto::getCompanyName).orElse(null));

        URL urlPath = new URL(resultModel.getData().getCodeUrl());
        IOUtils.copy(urlPath.openStream(), response.getOutputStream());
        response.getOutputStream().flush();
    }

    @ApiOperation(value = "企业选择列表")
    @PostMapping("list/select")
    @SecurityAuthCheck
    public ResultModel<CompanyListSelectResponse> select(CompanyListSelectRequest request) {

        String nameLike = SqlUtil.like(request.getName());
        List<Company> companies = companyApiAdminMapper.selectList(nameLike);
        List<CompanyListSelectResponse.Company> companyList = ConvertUtils.list(companies, company -> {
            return CompanyListSelectResponse.Company.builder()
                    .id(company.getCompanyId())
                    .name(company.getCompanyName())
                    .build();
        });

        CompanyListSelectResponse response = CompanyListSelectResponse.builder()
                .goods(companyList)
                .build();
        return ResultModel.success(response);
    }
}
